<template>
<view class="container">
  <view class="coupon_list" v-if="showCoupon&&showCoupon.length!=0">
    <view class="coupon_item" v-for="(cou, index) in showCoupon" :key="index" :data-id="cou.id">
      <view class="parting_line">
        <text class="circle"></text>
        <text class="circle"></text>
      </view>
      <view class="coupon_random_type" :style="'background:' + setting.platformSetting.defaultColor" v-if="cou.randomAmountType!=0">
        <text>最高可得</text>
      </view>
      <view class="coupon_item_top">
        <view class="coupon_item_top_left">
          <view class="coupon_money" :style="'color:' + setting.platformSetting.defaultColor">
            <text style="letter-spacing:-8rpx;font-size:24rpx">￥</text>{{cou.youhuiAmount}}
          </view>
          <view class="coupon_type" :style="'color:' + setting.platformSetting.defaultColor">
            <text v-if="cou.orderAmount!=0">满{{cou.orderAmount}}元可用</text>
            <text v-else>无金额门槛</text>
          </view>
        </view>
        <view class="coupon_item_top_center">
          <text class="coupon_item_name">{{cou.name}}</text>
          <text class="coupon_item_time" v-if="cou.endDateType==1">领取后{{cou.endDateCount}}天内有效</text>
          <text class="coupon_item_time" v-else>有效期至 {{cou.endDate}}</text>
        </view>
        <view class="coupon_item_top_right">
          <block v-if="cou.gotCount>=cou.count&&!cou.userGotCoupon.length">
            <view class="cou_btn">已领完</view>
          </block>
          <block v-else-if="!cou.userCanGot">
            <view class="cou_btn">已领取</view>
          </block>
          <block v-else>
            <view class="cou_btn" :style="'background:' + setting.platformSetting.defaultColor" :data-id="cou.id" @click.stop="GotCoupon">立即领取</view>
          </block>
        </view>
      </view>
      <view class="coupon_item_bottom">
        <view class="coupon_item_bottom_remark">
          <text v-if="cou.belongShopId&&cou.belongShopId!=0">【仅限于{{cou.belongShopName}}内使用】</text>
          {{cou.remark}}
        </view>
      </view>
    </view>
  </view>
  <view class="noList" v-else>
    <text>主人~暂时还没有任何可领取的优惠券哦！</text>
  </view>
</view>
</template>

<script>

export default {
  data() {
    return {
      showCoupon: [],
      listPage: {
        page: 1,
        pageSize: 0,
        totalSize: 0,
        curpage: 1
      },
      setting: "",
      loginUser: ""
    };
  },

  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getNewCouponsList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.setData({
      setting: getApp().globalData.setting
    });
    this.setData({
      loginUser: getApp().globalData.loginUser
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.showCoupon = [];
    this.listPage.page = 1;
    this.getNewCouponsList();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;

    if (that.listPage.totalSize > that.listPage.curPage * that.listPage.pageSize) {
      that.listPage.page++;
      this.getNewCouponsList();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return getApp().globalData.shareForFx('available_coupons');
  },
  methods: {
    //领取优惠券
    GotCoupon: function (e) {
      //gain_coupon
      var data = {
        couponId: '',
        couponSecretCode: '',
        couponSecretPassword: ''
      };
      data.couponId = e.currentTarget.dataset.id;
      console.log(data);
      var that = this;
      var customIndex = getApp().globalData.AddClientUrl("/gain_coupon.html", data, 'post');
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.headerPost,
        data: customIndex.params,
        method: 'POST',
        success: function (res) {
          console.log('---------s---------', res.data);
          let gainData = res.data;

          if (!res.data.errcode) {
            wx.showToast({
              title: '领取成功',
              icon: 'success',
              duration: 1000
            });
            that.freshData(gainData);
          } else {
            wx.showToast({
              title: res.data.errMsg,
              icon: 'none',
              duration: 1000
            });
          }
        },
        fail: function (res) {
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },
    freshData: function (gainData) {
      console.log("1111111111");
      let showCoupon = this.showCoupon;

      for (let i = 0; i < showCoupon.length; i++) {
        if (showCoupon[i].id == gainData.id) {
          showCoupon.splice(i, 1, gainData.coupon);
        }
      }

      this.setData({
        showCoupon: showCoupon
      });
    },

    /* 去掉日期的时间 */
    spliceData: function (e) {
      for (let i = 0; i < e.length; i++) {
        e[i].startDate = e[i].startDate.substring(0, 10);
        e[i].endDate = e[i].endDate.substring(0, 10);
      }

      return e;
    },

    toCouponDetail(data) {
      console.log("--------toCouponDetail------", data);
      console.log(data.currentTarget.dataset.id);
      var id = data.currentTarget.dataset.id;
      wx.navigateTo({
        url: '../../pages/coupon_detail/index?couponId=' + id
      });
    },

    getNewCouponsList: function () {
      var that = this;
      var getParam = {};
      getParam.page = that.listPage.page;
      var customIndex = getApp().globalData.AddClientUrl("/get_available_coupons.html", getParam);
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log(res.data);
          that.listPage.pageSize = res.data.pageSize;
          that.listPage.curPage = res.data.curPage;
          that.listPage.totalSize = res.data.totalSize;
          let dataArr = that.showCoupon;
          dataArr = dataArr.concat(res.data.result);
          var result = that.spliceData(dataArr);
          that.setData({
            showCoupon: result
          });
        },
        fail: function (res) {
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>